<template>
  <contents :heightInclude="['tabBar']" class="register_page">
    <u-form
      :model="form"
      ref="form"
      class="register_form"
      label-width="165"
      :label-style="{ paddingRight: '15rpx' }"
    >
      <u-form-item
        :label="$t('locales.region')"
        prop="countryName"
        v-if="form.type === 0"
      >
        <u-input
          :border="false"
          type="select"
          :select-open="showCountry"
          v-model="form.countryName"
          :placeholder="$t('locales.switchRgeion')"
          @click="showCountry = true"
        ></u-input>
      </u-form-item>
      <template v-if="form.type === 0">
        <u-form-item :label="$t('locales.phone')" prop="mobile">
          <u-input
            v-model="form.mobile"
            :placeholder="$t('locales.inputPhone')"
            type="number"
            @blur="
              $store.dispatch('CheckRegisterIn', {
                username: form.mobile,
                accountType: 2,
                pageType: 1
              })
            "
          />
        </u-form-item>
        <u-form-item :label="$t('locales.SMSCode')" prop="validateCode">
          <u-input
            type="number"
            maxlength="6"
            v-model="form.validateCode"
            :placeholder="$t('locales.inputSMSCode')"
          />
          <SetCode
            :disabled="form.countryName == '' || $store.getters.accountRepeat"
            slot="right"
            :phone="form.mobile"
            uniqueKey="register"
            :request="{ mobileAttribution: form.mobileAttribution }"
          />
        </u-form-item>
      </template>
      <template v-if="form.type === 1">
        <u-form-item :label="$t('locales.email')" prop="email">
          <u-input
            v-model="form.email"
            :placeholder="$t('locales.inputEmail')"
            @blur="
              $store.dispatch('CheckRegisterIn', {
                username: form.email,
                accountType: 1,
                pageType: 1
              })
            "
          />
        </u-form-item>
        <u-form-item :label="$t('locales.emailCode')" prop="validateCode">
          <u-input
            type="number"
            maxlength="6"
            v-model="form.validateCode"
            :placeholder="$t('locales.inputSMSCode')"
          />
          <SetCode
            slot="right"
            :phone="form.email"
            uniqueKey="register"
            :disabled="$store.getters.accountRepeat"
          />
        </u-form-item>
      </template>
      <u-form-item :label="$t('locales.pwd')" prop="password">
        <u-input
          maxlength="20"
          v-model="form.password"
          :placeholder="$t('locales.pleaseEnterPassword')"
          type="password"
        />
      </u-form-item>
    </u-form>
    <u-picker
      v-model="showCountry"
      mode="selector"
      :range="countryList"
      range-key="country"
      @confirm="pickerConfirm"
    ></u-picker>
    <view style="height: 132rpx"></view>
    <SubmitBtn
      :disabled="$store.getters.accountRepeat"
      :fixed="false"
      :text="$t('locales.pages/user/register/index')"
      @click="submit"
    />
    <view
      @click="switchRegType"
      style="text-align: center; color: #2457e0; text-decoration: underline"
    >
      {{
        form.type === 0
          ? $t('locales.emailRegister')
          : $t('locales.phoneRegister')
      }}
    </view>
  </contents>
</template>

<script>
import SetCode from '@/components/setSmsCode'
import SubmitBtn from '@/components/submitBtn'
import { Base64 } from '@/util/base64'
import { register, getCountryCurrencyList } from '@/api/http/user'
export default {
  components: {
    SetCode,
    SubmitBtn
  },
  data() {
    return {
      form: {
        mobileAttribution: '',
        countryName: '',
        type: 0, // 0 手机 or 1 邮箱
        mobile: '',
        email: '',
        username: '', // 手机或者邮箱
        validateCode: '', // 验证码
        password: '' // 密码
      },
      showCountry: false,
      countryList: [],
      rules: {
        countryName: [
          {
            required: true,
            message: this.$t('locales.switchRgeion'),
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: this.$t('locales.inputPhone'),
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: this.$t('locales.inputEmail'),
            trigger: ['change', 'blur']
          },
          {
            validator: (rule, value, callback) => {
              return this.$u.test.email(value)
            },
            message: this.$t('locales.emailErr'),
            trigger: ['change', 'blur']
          }
        ],
        validateCode: [
          {
            required: true,
            message: this.$t('locales.inputSMSCode'),
            trigger: 'blur'
          },
          {
            min: 6,
            message: this.$t('locales.digitErr'),
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: this.$t('locales.inputPwd'),
            trigger: 'blur'
          },
          {
            min: 6,
            message: this.$t('locales.digitPwdErr'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  onLoad() {
    this.getData()
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  methods: {
    getData() {
      getCountryCurrencyList().then((res) => {
        if (res.code === 200) {
          this.countryList = res.data
        } else {
          uni.showToast({
            icon: 'none',
            title: res.message
          })
        }
      })
    },
    pickerConfirm(row) {
      const data = this.countryList[row[0]]
      this.form.mobileAttribution = data.id
      this.form.countryName = data.country
    },
    // 切换注册方式
    switchRegType() {
      this.form.type === 0 ? (this.form.type = 1) : (this.form.type = 0)
      this.$refs.form.resetFields()
    },
    // 提交注册
    submit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return
        // Base64加盐
        let formData = this.$u.deepClone(this.form)
        formData.password = Base64.encode(this.form.password)
        // 区分邮箱和手机
        formData.username =
          this.form.type === 0 ? this.form.mobile : this.form.email
        register({
          ...formData,
          domainPrefix: this.$store.getters.domainPrefix || '',
          // #ifdef H5
          customerTerminal: '1',
          // #endif

          // #ifdef APP-PLUS
          customerTerminal: '2'
          // #endif
        }).then((res) => {
          uni.showToast({
            icon: 'none',
            title: res.message
          })
          if (res.code === 200) {
            this.$store.commit('SET_USER_INFO', res.data)
            this.$store.commit('SET_LOGIN_BACK', true)
            this.$store.commit('SET_LOGIN_STATE')
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/index/home/index'
              })
            }, 700)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss">
.register_page {
  .u-form {
    padding: 0 30rpx;
    background-color: #fff;
  }
}
</style>
